<?php
/**
 * 
 * Copyright (c) 2008 Jerry Jalava <jerry.jalava@gmail.com>
 * Licensed under the GPLv3 license
 * http://www.gnu.org/licenses/gpl.html
 * 
 */

require_once('couchdb/exceptions.php');

class couchdb_connection
{    
    public $database;
    public $can_connect = false;
    
    private $configuration;
    
    public function __construct(array $config=array())
    {        
        if (! isset($config['host']))
        {
            $config['host'] = 'localhost';
        }

        if (! isset($config['port']))
        {
            $config['port'] = 5984;
        }
        
        spl_autoload_register(array($this, 'autoload'));
        
        $this->configuration = $config;
        
        $this->can_connect = $this->can_connect();
        
        $this->database = new couchdb_databases(&$this->configuration);
    }
    
    public function __get($name)
    {
        return $this->database->$name;
    }
    
    public function __isset($name)
    {
        return isset($this->database->$name);
    }
    
    public function all_databases($names_only=false)
    {
        return $this->database->get_all($names_only);
    }
    
    public function new_replicator($configuration=array(), $backend='http')
    {
        $classname = "couchdb_replicator_{$backend}";
        
        if (! class_exists($classname))
        {
            throw new couchdb_replicator_exception("No {$backend} backend found!");
        }

        $replicator = new $classname($this->configuration, $configuration);
        
        return $replicator;
    }
    
    public function clear_caches()
    {
        $this->database->clear_caches();
    }
    
    private function can_connect()
    {
        $socket = @fsockopen($this->configuration['host'], $this->configuration['port'], $errno = -1, $errstr = '', $timeout = 10);
        
        if (! $socket)
        {
            throw new couchdb_connection_exception("Couldn't connect to server at {$this->configuration['host']}:{$this->configuration['port']}");
        }
        
        @fclose($socket);        
        
        return true;
    }
    
    static function autoload($class_name)
    {
        if (class_exists($class_name))
        {
            return;
        }
        
        $path = str_replace('_', '/', $class_name) . '.php';

        if (file_exists($path))
        {
            require_once($path);
        }
    }
}

?>